<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/database/core/Database.php';

class MySQLUtils
{
	const kMaxCreateErrors = 3;
	private static $createTableErrors      = 0;
	
	public static function createDatabase()
	{
		$config = PhormConfig::getConfig();

		$query = "CREATE DATABASE IF NOT EXISTS ".$config->databaseName;
		$dbh = new PDO($config->databaseType.':host='.$config->databaseHost, $config->databaseUsername, $config->databasePassword);
		$dbh->query($query);
		Database::finish();
	}
	
	public static function createTables()
	{
		echo '<h3>Creating Base Tables</h3>';
		
		$config    = PhormConfig::getConfig();
		$dbh       = Database::persistentConnection();
		$classes   = get_declared_classes();
		$hasErrors = false;
		
		foreach($classes as $class)
		{
			if (get_parent_class($class) == "MySQLRecord")
			{
				$c      = new $class();
				$result = $dbh->query($c->create());
				
				if($result->errorCode() === '00000')
				{
					echo '<div>(<span style="color:#00cc00">success</span>) <i>'.$class.'</i></div>';
					echo '<div id="'.$class.'" style="display:none;"><pre>',$c->create(),'</pre></div>';
				}
				else
				{
					$hasErrors = true;
					echo '<div>(<span style="color:#cc0000">fail</span>) <i>'.$class.'</i></div>';
				}
				
				$c->__destruct();
				$c = null;
			}
		}
		
		//Database::finish();
		
		if($hasErrors && self::$createTableErrors < MySQLUtils::kMaxCreateErrors)
		{
			echo '<div>Errors Exist! Attempting to create tables again('.self::$createTableErrors.')...</div>';
			echo '<div>Attempts Remaining:'.(self::MAX_CREATE_ERRORS - self::$createTableErrors).'</div>';
			self::$createTableErrors++;
			self::createTables();
		}
		else
		{
			self::createPivotTables();
		}
	}
	
	public static function createPivotTables()
	{
		echo '<h3>Creating Pivot Tables</h3>';
		
		$dbh       = Database::persistentConnection();
		$classes   = get_declared_classes();
		
		foreach($classes as $class)
		{
			if (get_parent_class($class) == "MySQLRecord")
			{
				$c = new $class();
				foreach($c->columns as $key=>$value)
				{
					if ($value instanceof ManyToMany )
					{
						$result = $dbh->query($value->create());
						if($result->errorCode() === '00000')
						{
							echo '<div>(<span style="color:#00cc00">success</span>) <i>'.$class.'->'.$key.'</i></div>';
						}
						else
						{
							echo '<div>(<span style="color:#cc0000">fail</span>) <i>'.$class.'->'.$key.'</i></div>';
						}
					}
				}
				
				$c->__destruct();
			}
		}
		
		self::createPrimaryKeyUUIDTriggers();
	}
	
	public static function createPrimaryKeyUUIDTriggers()
	{
		echo '<h3>Creating PrimaryKey UUID Triggers</h3>';
		
		$dbh       = Database::persistentConnection();
		$classes   = get_declared_classes();
		
		foreach($classes as $class)
		{
			if (get_parent_class($class) == "MySQLRecord")
			{
				$c = new $class();
				foreach($c->columns as $key=>$value)
				{
					if ($value instanceof PrimaryKey && $value->field_type == 'uuid')
					{
						$result = $dbh->query(MySQLCRUD::createUUIDTrigger($c, $value));
						if($result->errorCode() === '00000')
						{
							echo '<div>(<span style="color:#00cc00">success</span>) <i>UUID Trigger:'.$class.'->'.$key.'</i></div>';
						}
						else
						{
							echo '<div>(<span style="color:#cc0000">fail</span>) <i>UUID Trigger:'.$class.'->'.$key.'</i></div>';
						} 
					}
				}
				
				$c->__destruct();
			}
		}
		
		Database::finish();
	}

	public static function emptyTables()
	{
		$config = PhormConfig::getConfig();

		$dbh = Database::persistentConnection();

		$classes = get_declared_classes();

		foreach($classes as $class)
		{
			if (get_parent_class($class) == "MySQLRecord")
			{
				$c = new $class();
				$dbh->query($c->emptyThis());
				$c = null;
			}
		}
		Database::finish();
	}

	public static function dropTables()
	{
		$config = PhormConfig::getConfig();

		$dbh = Database::persistentConnection();

		$classes = get_declared_classes();

		foreach($classes as $class)
		{
			if (get_parent_class($class) == "MySQLRecord")
			{
				$c = new $class();
				$dbh->query($c->drop());
				$c = null;
			}
		}
		Database::finish();
	}
}
?>
